package handler

import (
	"car-order-mgr/cache"
	"car-order-mgr/models"
	"car-order-mgr/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	jsoniter "github.com/json-iterator/go"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user models.User
	redis_key := "login_" + username
	errData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	err := models.DB.Where("username=?", username).Debug().First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func CreateRoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	nid, _ := strconv.Atoi(c.Query("nid"))
	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.RoleNode{
		Rid: nid,
		Nid: nid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "关联成功",
		"data": data,
	})
	return
}
func QueryUserRole(c *gin.Context) {
	/*
		SELECT
		*
		FROM
		roles
		LEFT JOIN user_roles ON roles.id=user_roles.uid
	*/
	uid := c.Query("uid")
	var role models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id=user_roles.uid").
		Where("user_roles.uid=?", uid).Debug().First(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": role,
	})
	return
}
func QueryRoleNode(c *gin.Context) {
	/*
		SELECT
		*
		FROM
		nodes
		LEFT JOIN role_nodes ON nodes.id=role_nodes.rid
	*/
	rid := c.Query("rid")
	var node models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id=role_nodes.rid").
		Where("role_nodes.rid=?", rid).Debug().First(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": node,
	})
	return
}
func CreateCar(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	car_price := c.PostForm("car_price")
	if car_code == "" || car_name == "" || car_price == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Car{
		CarCode:  car_code,
		CarName:  car_name,
		CarPrice: car_price,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func CreateCarOrder(c *gin.Context) {
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	order_code := c.PostForm("order_code")
	order_name := c.PostForm("order_name")
	order_num, _ := strconv.Atoi(c.PostForm("order_num"))
	order_price := c.PostForm("order_price")
	if cid == 0 || order_code == "" || order_name == "" || order_num == 0 || order_price == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.CarOrder{
		Cid:        cid,
		OrderCode:  order_code,
		OrderName:  order_name,
		OrderNum:   order_num,
		OrderPrice: order_price,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func CarOrderList(c *gin.Context) {
	/*
			SELECT
		  car_orders.id OrderId,
		  cars.car_code CarCode,
		  cars.car_name CarName,
		  cars.car_price CarPrice,
		  car_orders.order_code OrderCode,
		  car_orders.order_name OrderName,
		  car_orders.order_num OrderNum,
		  car_orders.order_price OrderPrice
		FROM
		  car_orders
		  LEFT JOIN cars ON cars.id = car_orders.cid
	*/
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var carOrderList []models.CarOrderList
	redis_key := "car_order_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_orders").
			Select("car_orders.id OrderId,\n\t  cars.car_code CarCode,\n\t  cars.car_name CarName,\n\t  cars.car_price CarPrice,\n\t  car_orders.order_code OrderCode,\n\t  car_orders.order_name OrderName,\n\t  car_orders.order_num OrderNum,\n\t  car_orders.order_price OrderPrice").
			Joins("LEFT JOIN cars ON cars.id=car_orders.cid").
			Offset(offset).Limit(size).Debug().Find(&carOrderList)
		jsonData, _ := jsoniter.Marshal(&carOrderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		jsoniter.Unmarshal([]byte(cacheData), &carOrderList)
	}
	var total int64
	models.DB.Table("car_orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表成功",
		"data":  carOrderList,
		"total": total,
	})
	return
}
func CarOrderDetail(c *gin.Context) {
	/*
		SELECT
		  car_orders.id OrderId,
		  cars.car_code CarCode,
		  cars.car_name CarName,
		  cars.car_price CarPrice,
		  car_orders.order_code OrderCode,
		  car_orders.order_name OrderName,
		  car_orders.order_num OrderNum,
		  car_orders.order_price OrderPrice
		FROM
		  car_orders
		  LEFT JOIN cars ON cars.id = car_orders.cid
		  WHERE
		  car_orders.cid=1
	*/
	id := c.Query("id")
	var carOrderList models.CarOrderList
	redis_key := "car_order_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_orders").
			Select("car_orders.id OrderId,\n\t  cars.car_code CarCode,\n\t  cars.car_name CarName,\n\t  cars.car_price CarPrice,\n\t  car_orders.order_code OrderCode,\n\t  car_orders.order_name OrderName,\n\t  car_orders.order_num OrderNum,\n\t  car_orders.order_price OrderPrice").
			Joins("LEFT JOIN cars ON cars.id=car_orders.cid").
			Where("car_orders.cid=?", id).Debug().Find(&carOrderList)
		jsonData, _ := jsoniter.Marshal(&carOrderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		jsoniter.Unmarshal([]byte(cacheData), &carOrderList)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表成功",
		"data": carOrderList,
	})
	return
}
